<template>
  <view class="w-[750rpx] min-h-screen bg-[#f5f5f5] flex flex-col">
    <view class="px-[32rpx] pt-[40rpx] pb-[24rpx]">
      <view class="bg-white rounded-[32rpx] shadow-[0_12rpx_36rpx_rgba(22,93,255,0.08)] px-[32rpx] py-[28rpx] flex flex-col gap-[24rpx]">
        <view class="flex items-center justify-between">
          <text class="text-[36rpx] font-semibold text-[#165DFF]">调试日志</text>
          <nut-button
            type="primary"
            size="small"
            class="bg-[#165DFF] text-white border-none rounded-[24rpx] px-[36rpx] text-[26rpx] py-[10rpx]"
            @click="handleClear"
          >
            清空日志
          </nut-button>
        </view>
        <view class="flex flex-col gap-[24rpx]">
          <view class="flex items-center gap-[20rpx]">
            <nut-button
              type="primary"
              size="small"
              class="bg-[#165DFF] text-white border-none rounded-[24rpx] px-[24rpx] text-[26rpx] py-[12rpx]"
              @click="handleWxLocation"
            >
              微信获取定位
            </nut-button>
            <nut-button
              type="default"
              size="small"
              class="border border-[#165DFF] text-[#165DFF] rounded-[24rpx] px-[24rpx] text-[26rpx] py-[12rpx]"
              @click="handleBrowserLocation"
            >
              浏览器获取定位
            </nut-button>
          </view>
          <view v-if="locationPreview" class="bg-[#f5f5f5] rounded-[24rpx] p-[24rpx]">
            <view class="flex items-center justify-between mb-[12rpx]">
              <text class="text-[28rpx] font-semibold text-[#165DFF]">
                {{ locationPreview.source === 'wx-sdk' ? '微信定位结果' : locationPreview.source === 'browser' ? '浏览器定位结果' : '定位状态' }}
              </text>
              <text class="text-[24rpx] text-[#999]">
                {{ locationPreview.time }}
              </text>
            </view>
            <view v-if="locationPreview.success" class="flex flex-col gap-[12rpx] text-[26rpx] text-[#333] leading-[36rpx]">
              <text>地址：{{ locationPreview.address || '无地址信息' }}</text>
              <text>坐标：{{ locationPreview.latitude }}, {{ locationPreview.longitude }}</text>
            </view>
            <view v-else class="text-[26rpx] text-[#FF4D4F] leading-[36rpx]">
              {{ locationPreview.errorMessage }}
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="flex-1 px-[32rpx] pb-[40rpx]">
      <view class="bg-white rounded-[32rpx] shadow-[0_10rpx_30rpx_rgba(0,0,0,0.08)] p-[32rpx] min-h-[400rpx]">
        <view v-if="isEmpty" class="flex flex-col items-center justify-center py-[120rpx]">
          <nut-empty description="暂无调试日志" />
        </view>
        <view v-else class="flex flex-col gap-[24rpx]">
          <view
            v-for="log in logs"
            :key="log.timestamp"
            class="bg-[#f5f5f5] rounded-[24rpx] p-[24rpx]"
          >
            <text class="block text-[26rpx] text-[#165DFF] font-medium mb-[12rpx]">
              {{ formatDate(log.timestamp) }}
            </text>
            <text class="text-[28rpx] text-[#333] leading-[40rpx] break-words">
              {{ log.message }}
            </text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { computed, ref } from "vue";
import Taro, { useDidShow } from "@tarojs/taro";
import { useUserStore } from "@/store/user";

declare const wx: any;

const DEBUG_LOG_STORAGE_KEY = "authDebugLogs";

interface DebugLogEntry {
  timestamp: number;
  message: string;
}

const logs = ref<DebugLogEntry[]>([]);
const userStore = useUserStore();
const locationPreview = ref<{
  source: "wx-sdk" | "browser" | "error";
  success: boolean;
  address?: string;
  latitude?: number;
  longitude?: number;
  errorMessage?: string;
  time: string;
} | null>(null);

const updateLocationPreview = (payload: {
  source: "wx-sdk" | "browser" | "error";
  success: boolean;
  address?: string;
  latitude?: number;
  longitude?: number;
  errorMessage?: string;
}) => {
  locationPreview.value = {
    ...payload,
    time: formatDate(Date.now()),
  };
};

/**
 * 加载调试日志，并按时间正序排序
 * @performance 使用内存缓存和长度裁剪，避免渲染过多节点影响滚动性能
 */
const loadLogs = () => {
  try {
    const cache: DebugLogEntry[] = Taro.getStorageSync(DEBUG_LOG_STORAGE_KEY) || [];
    logs.value = [...cache].sort((a, b) => a.timestamp - b.timestamp);
  } catch (error) {
    Taro.showToast({
      title: "读取日志失败",
      icon: "none",
    });
  }
};

const isEmpty = computed(() => logs.value.length === 0);

/**
 * 清空调试日志缓存
 */
const handleClear = () => {
  Taro.showModal({
    title: "提示",
    content: "确定要清空所有调试日志吗？",
    success: (res) => {
      if (res.confirm) {
        Taro.removeStorageSync(DEBUG_LOG_STORAGE_KEY);
        logs.value = [];
        Taro.showToast({
          title: "已清空",
          icon: "success",
        });
      }
    },
  });
};

/**
 * 调用微信SDK获取定位
 * @description 需要在微信环境下调用
 */
const handleWxLocation = async () => {
  if (!wx || typeof wx.getLocation !== "function") {
    Taro.showToast({
      title: "当前环境不支持微信定位",
      icon: "none",
    });
    return;
  }

  Taro.showLoading({ title: "微信定位中..." });
  try {
    await userStore.getLocation("wx-sdk");
    const data = userStore.locationObj;
    updateLocationPreview({
      source: "wx-sdk",
      success: true,
      address: data?.address || data?.formatted_addresses?.standard_address,
      latitude: data?.location?.lat || data?.ad_info?.location?.lat,
      longitude: data?.location?.lng || data?.ad_info?.location?.lng,
    });
    Taro.showToast({ title: "微信定位成功", icon: "success" });
  } catch (error) {
    console.error("微信定位失败:", error);
    updateLocationPreview({
      source: "error",
      success: false,
      errorMessage: error instanceof Error ? error.message : String(error),
    });
    Taro.showToast({ title: "微信定位失败", icon: "none" });
  } finally {
    Taro.hideLoading();
  }
};

/**
 * 调用浏览器定位API
 * @description 适用于调试或非微信环境
 */
const handleBrowserLocation = async () => {
  if (!navigator.geolocation) {
    Taro.showToast({
      title: "浏览器不支持定位",
      icon: "none",
    });
    return;
  }

  Taro.showLoading({ title: "浏览器定位中..." });
  try {
    await userStore.getLocation("browser");
    const data = userStore.locationObj;
    updateLocationPreview({
      source: "browser",
      success: true,
      address: data?.address || data?.formatted_addresses?.standard_address,
      latitude: data?.location?.lat || data?.ad_info?.location?.lat,
      longitude: data?.location?.lng || data?.ad_info?.location?.lng,
    });
    Taro.showToast({ title: "浏览器定位成功", icon: "success" });
  } catch (error) {
    console.error("浏览器定位失败:", error);
    updateLocationPreview({
      source: "error",
      success: false,
      errorMessage: error instanceof Error ? error.message : String(error),
    });
    Taro.showToast({ title: "浏览器定位失败", icon: "none" });
  } finally {
    Taro.hideLoading();
  }
};

/**
 * 将时间戳格式化为可读文本
 * @param timestamp 日志时间戳
 */
const formatDate = (timestamp: number) => {
  const date = new Date(timestamp);
  const yyyy = date.getFullYear();
  const mm = String(date.getMonth() + 1).padStart(2, "0");
  const dd = String(date.getDate()).padStart(2, "0");
  const hh = String(date.getHours()).padStart(2, "0");
  const mi = String(date.getMinutes()).padStart(2, "0");
  const ss = String(date.getSeconds()).padStart(2, "0");
  return `${yyyy}-${mm}-${dd} ${hh}:${mi}:${ss}`;
};

useDidShow(() => {
  loadLogs();
});
</script>

